/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jy.appmarket.newnetwork.toolbox;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.zip.GZIPInputStream;

import com.jy.appmarket.newnetwork.AuthFailureError;
import com.jy.appmarket.newnetwork.Cache;
import com.jy.appmarket.newnetwork.Cache.Entry;
import com.jy.appmarket.newnetwork.Network;
import com.jy.appmarket.newnetwork.NetworkError;
import com.jy.appmarket.newnetwork.NetworkLog;
import com.jy.appmarket.newnetwork.NetworkResponse;
import com.jy.appmarket.newnetwork.NoConnectionError;
import com.jy.appmarket.newnetwork.Request;
import com.jy.appmarket.newnetwork.RetryPolicy;
import com.jy.appmarket.newnetwork.ServerError;
import com.jy.appmarket.newnetwork.TimeoutError;
import com.jy.appmarket.newnetwork.VolleyError;
import com.jy.appmarket.newnetwork.http.HttpEntity;
import com.jy.appmarket.newnetwork.http.HttpHeader;
import com.jy.appmarket.newnetwork.http.HttpResponse;

import android.os.SystemClock;

/**
 * A network performing Volley requests over an {@link HttpStack}.
 */
public class BasicNetwork implements Network {
	protected static final boolean DEBUG = NetworkLog.DEBUG;

	private static int SLOW_REQUEST_THRESHOLD_MS = 3000;

	protected final HurlStack mUrlStack;

	public BasicNetwork(HurlStack urlStack) {
		mUrlStack = urlStack;
	}

	@Override
	public NetworkResponse performRequest(Request<?> request) throws VolleyError {
		long requestStart = SystemClock.elapsedRealtime();
		while (true) {
			HttpResponse httpResponse = null;
			byte[] responseContents = null;
			Map<String, String> responseHeaders = Collections.emptyMap();
			try {
				// Gather headers.
				Map<String, String> headers = new HashMap<String, String>();
				// 打开gzip
				headers.put("Accept-Encoding", "gzip");
				addCacheHeaders(headers, request.getCacheEntry());

				httpResponse = mUrlStack.performRequest(request, headers);

				responseHeaders = convertHeaders(httpResponse.getAllHeaders());
				int statusCode = httpResponse.getStatusCode();

				if (statusCode == 304) {
					Entry entry = request.getCacheEntry();
					if (entry == null) {
						return new NetworkResponse(304, null, responseHeaders, true,
								SystemClock.elapsedRealtime() - requestStart);
					}

					// A HTTP 304 response does not have all header fields. We
					// have to use the header fields from the cache entry plus
					// the new ones from the response.
					// http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
					entry.responseHeaders.putAll(responseHeaders);
					return new NetworkResponse(304, entry.data, entry.responseHeaders, true,
							SystemClock.elapsedRealtime() - requestStart);
				}

				// Some responses such as 204s do not have content. We must
				// check.
				if (httpResponse.getEntity() != null) {
					responseContents = entityToBytes(httpResponse.getEntity());
				} else {
					// Add 0 byte response as a way of honestly representing a
					// no-content request.
					responseContents = new byte[0];
				}

				// if the request is slow, log it.
				long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
				logSlowRequests(requestLifetime, request, responseContents, statusCode);

				if (statusCode < 200 || statusCode > 299) {
					throw new IOException();
				}
				return new NetworkResponse(statusCode, responseContents, responseHeaders, false,
						SystemClock.elapsedRealtime() - requestStart);
			} catch (SocketTimeoutException e) {
				attemptRetryOnException("socket", request, new TimeoutError());
			} catch (MalformedURLException e) {
				throw new RuntimeException("Bad URL " + request.getUrl(), e);
			} catch (IOException e) {
				int statusCode = 0;
				NetworkResponse networkResponse = null;
				if (httpResponse != null) {
					statusCode = httpResponse.getStatusCode();
				} else {
					throw new NoConnectionError(e);
				}
				NetworkLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
				if (responseContents != null) {
					networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false,
							SystemClock.elapsedRealtime() - requestStart);
					if (statusCode == 401 || statusCode == 403) {
						attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
					} else {
						throw new ServerError(networkResponse);
					}
				} else {
					throw new NetworkError(networkResponse);
				}
			}
		}
	}

	/**
	 * Logs requests that took over SLOW_REQUEST_THRESHOLD_MS to complete.
	 */
	private void logSlowRequests(long requestLifetime, Request<?> request, byte[] responseContents, int statusCode) {
		if (DEBUG || requestLifetime > SLOW_REQUEST_THRESHOLD_MS) {
			NetworkLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " + "[rc=%d], [retryCount=%s]",
					request, requestLifetime, responseContents != null ? responseContents.length : "null", statusCode,
					request.getRetryPolicy().getCurrentRetryCount());
		}
	}

	/**
	 * Attempts to prepare the request for a retry. If there are no more
	 * attempts remaining in the request's retry policy, a timeout exception is
	 * thrown.
	 * 
	 * @param request
	 *            The request to use.
	 */
	private static void attemptRetryOnException(String logPrefix, Request<?> request, VolleyError exception)
			throws VolleyError {
		RetryPolicy retryPolicy = request.getRetryPolicy();
		int oldTimeout = request.getTimeoutMs();

		try {
			retryPolicy.retry(exception);
		} catch (VolleyError e) {
			request.addMarker(String.format("%s-timeout-giveup [timeout=%s]", logPrefix, oldTimeout));
			throw e;
		}
		request.addMarker(String.format("%s-retry [timeout=%s]", logPrefix, oldTimeout));
	}

	public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";

	private void addCacheHeaders(Map<String, String> headers, Cache.Entry entry) {
		// If there's no cache entry, we're done.
		if (entry == null) {
			return;
		}

		if (entry.etag != null) {
			headers.put("If-None-Match", entry.etag);
		}

		if (entry.lastModified > 0) {
			Date refTime = new Date(entry.lastModified);
			SimpleDateFormat formatter = new SimpleDateFormat(PATTERN_RFC1123, Locale.US);
			formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
			headers.put("If-Modified-Since", formatter.format(refTime));
		}
	}

	protected void logError(String what, String url, long start) {
		long now = SystemClock.elapsedRealtime();
		NetworkLog.v("HTTP ERROR(%s) %d ms to fetch %s", what, (now - start), url);
	}

	/** Reads the contents of HttpEntity into a byte[]. */
	private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
		// transfer mode 为trunk的时候ContentLength < 0
		int initSize = Math.max(entity.getContentLength(), 1024 * 4);
		ByteArrayOutputStream baos = new ByteArrayOutputStream(initSize);
		byte[] buffer = new byte[10240];
		try {
			InputStream in = entity.getContent();
			if (in == null) {
				throw new ServerError();
			}
			if ("gzip".equals(entity.getContentEncoding())) {
				in = new GZIPInputStream(in);
			}

			int count;
			while ((count = in.read(buffer)) != -1) {
				baos.write(buffer, 0, count);
			}
			return baos.toByteArray();
		} finally {
			try {
				entity.consumeContent();
			} catch (IOException e) {
				// This can happen if there was an exception above that left the
				// entity in an invalid state.
				NetworkLog.v("Error occured when calling consumingContent");
			}
			safeClose(baos);
		}
	}

	/**
	 * Converts Headers[] to Map<String, String>.
	 */
	protected static Map<String, String> convertHeaders(HttpHeader[] headers) {
		Map<String, String> result = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
		for (int i = 0; i < headers.length; i++) {
			result.put(headers[i].getName(), headers[i].getValue());
		}
		return result;
	}

	private static void safeClose(Closeable c) {
		if (c == null) {
			return;
		}
		try {
			c.close();
		} catch (IOException e) {
		}
	}
}
